//
//  MTool.m
//  DongLe
//
//  Created by up72_01 on 15/8/21.
//  Copyright (c) 2015年 up72_01. All rights reserved.
//

#import "MTool.h"



static UIView *hudView = nil;
static CGRect oldframe;
static NSString *token;

static NSInteger BottomBarButtonIndex;

#define DESKEY @"3b38e11ffd65698aedeb5ffc"




@implementation MTool

+ (NSInteger)getBottomBarButtonIndex {
    return BottomBarButtonIndex;
}
+ (void)setBottomBarButtonIndex:(NSInteger)sender {
    BottomBarButtonIndex = sender;
}


+ (void)setToken:(NSString *)sender {
    token = [NSString stringWithFormat:@"%@", sender];
}

+ (NSString *)getToken {
    if (token) {
        if ([token length] > 0) {
            return token;
        }
    }
    return @"";
}

+ (CGFloat)getScreenWidth
{
    CGRect rect_screen = [[UIScreen mainScreen]bounds];
    CGSize size_screen = rect_screen.size;
    CGFloat scale_screen = [UIScreen mainScreen].scale;
    //    NSLog(@"当前分辨率：%fx%f",size_screen.height*scale_screen,size_screen.width *scale_screen);
    return size_screen.width *scale_screen;
}


+ (CGFloat)getScreenHeight
{
    CGRect rect_screen = [[UIScreen mainScreen]bounds];
    CGSize size_screen = rect_screen.size;
    CGFloat scale_screen = [UIScreen mainScreen].scale;
    return size_screen.height *scale_screen;
}

+ (BOOL)firstOpenApp
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    BOOL first = [[myDefault objectForKey:@"firstOpenApp"]boolValue];
    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"firstOpenApp"];
    [myDefault synchronize];
    return !first;
}

//提示框
+(void)showImage:(NSString *)image title:(NSString *)title inView:(UIView *)view withCGsize:(CGSize)size afterDelay:(CGFloat)timer
{
    if (!image||!view) {
        return;
    }
    
    if (hudView) {
        [hudView removeFromSuperview];
        hudView = nil;
    }
    hudView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    hudView.backgroundColor = [UIColor colorWithRed:(.0/255.0) green:(.0/255.0)  blue:(.0/255.0) alpha:.85];
    hudView.layer.cornerRadius = 5;
    hudView.layer.masksToBounds = YES;
    
    hudView.center = view.center;
    [view addSubview:hudView];
    hudView.hidden = NO;
    
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.frame = CGRectMake(size.width/3, 45, size.width/3, size.height/3);
    imageView.image = [UIImage imageNamed:image];
    imageView.hidden = NO;
    [hudView addSubview:imageView];
    
    if (title&&title.length) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 32*size.width/45, size.width-40, 17)];
        label.text = title;
        label.textColor = [UIColor whiteColor];
        label.numberOfLines = 1;
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:16.0f];
        label.textAlignment = NSTextAlignmentCenter;
        [hudView addSubview:label];
    }
    if (timer>0) {
        [self performSelector:@selector(hideImageView) withObject:nil afterDelay:timer];
    }
}

+ (void)hideImageView
{
    hudView.hidden = YES;
    [hudView removeFromSuperview];
    hudView = nil;
}

+(void)showImage:(UIImageView *)avatarImageView{
    UIImage *image=avatarImageView.image;
    UIWindow *window=[UIApplication sharedApplication].keyWindow;
    UIView *backgroundView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    oldframe=[avatarImageView convertRect:avatarImageView.bounds toView:window];
    backgroundView.backgroundColor=[UIColor blackColor];
    backgroundView.alpha=0;
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:oldframe];
    imageView.image=image;
    imageView.tag=1;
    [backgroundView addSubview:imageView];
    [window addSubview:backgroundView];
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImage:)];
    [backgroundView addGestureRecognizer: tap];
    
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame=CGRectMake(0,([UIScreen mainScreen].bounds.size.height-image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width)/2, [UIScreen mainScreen].bounds.size.width, image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width);
        backgroundView.alpha=1;
    } completion:^(BOOL finished) {
        
    }];
}

+(void)hideImage:(UITapGestureRecognizer*)tap{
    UIView *backgroundView=tap.view;
    UIImageView *imageView=(UIImageView*)[tap.view viewWithTag:1];
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame=oldframe;
        backgroundView.alpha=0;
    } completion:^(BOOL finished) {
        [backgroundView removeFromSuperview];
    }];
}

+ (NSString *) md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ] lowercaseString];
}

#pragma mark - 3des加解密
+ (NSString*)TripleDES:(NSString*)plainText encryptOrDecrypt:(CCOperation)encryptOrDecrypt
{
    
    const void *vplainText;
    size_t plainTextBufferSize;
    
    if (encryptOrDecrypt == kCCDecrypt)//解密
    {
        //        NSData *EncryptData = [GTMBase64 decodeData:[plainText dataUsingEncoding:NSUTF8StringEncoding]];
        NSData *EncryptData = [[NSData alloc] initWithBase64EncodedString:plainText options:0];
        plainTextBufferSize = [EncryptData length];
        vplainText = [EncryptData bytes];
    }
    else //加密
    {
        NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
        plainTextBufferSize = [data length];
        vplainText = (const void *)[data bytes];
    }
    
    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    
    bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    // memset((void *) iv, 0x0, (size_t) sizeof(iv));
    
    const void *vkey = (const void *) [DESKEY UTF8String];
    // NSString *initVec = @"init Vec";
    //const void *vinitVec = (const void *) [initVec UTF8String];
    //  Byte iv[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
    ccStatus = CCCrypt(encryptOrDecrypt,
                       kCCAlgorithm3DES,
                       kCCOptionPKCS7Padding | kCCOptionECBMode,
                       vkey,
                       kCCKeySize3DES,
                       nil,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);
    //if (ccStatus == kCCSuccess) NSLog(@"SUCCESS");
    /*else if (ccStatus == kCC ParamError) return @"PARAM ERROR";
     else if (ccStatus == kCCBufferTooSmall) return @"BUFFER TOO SMALL";
     else if (ccStatus == kCCMemoryFailure) return @"MEMORY FAILURE";
     else if (ccStatus == kCCAlignmentError) return @"ALIGNMENT";
     else if (ccStatus == kCCDecodeError) return @"DECODE ERROR";
     else if (ccStatus == kCCUnimplemented) return @"UNIMPLEMENTED"; */
    
    NSString *result;
    
    if (encryptOrDecrypt == kCCDecrypt)
    {
        result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes]
                                       encoding:NSUTF8StringEncoding] /*autorelease]*/;
    }
    else
    {
        NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
        //        result = [GTMBase64 stringByEncodingData:myData];
        result = [myData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }
    free(bufferPtr);
    bufferPtr = NULL;
    
    return result;
    
}




+ (void)showMessage:(NSString *)message inView:(UIView *)view
{
    if (!view)
    {
        AppDelegate *app =  (AppDelegate *)[UIApplication sharedApplication].delegate;
        view = app.window;
    }
    
    MAlertView *alertView = [[[NSBundle mainBundle] loadNibNamed:@"MAlertView" owner:nil options:nil] objectAtIndex:0];
    [alertView showWithTitle:message inView:view];
}

+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font constrainedToSize:(CGSize)size
{
    CGSize textSize = CGSizeZero;
    
    // 7.0 系统的适配处理。
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
    textSize = [text boundingRectWithSize:size
                                  options:NSStringDrawingUsesLineFragmentOrigin
                               attributes:tdic
                                  context:nil].size;
    
    return textSize;
}


#pragma mark - 将YYYY-MM-dd HH:mm:ss时间转换为MM-dd HH:mm的时间格式
/**
 * @brief   将YYYY-MM-dd HH:mm:ss时间转换为MM-dd HH:mm的时间格式
 * @param   uiDate    YYYY-MM-dd HH:mm:ss时间
 * @return  NSString   MM-dd HH:mm 时间
 */
+ (NSString *)convertDateStringFromString:(NSString*)uiDate {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.s"];
    NSDate *date=[formatter dateFromString:uiDate];
    
    [formatter setDateFormat:@"MM-dd HH:mm"];
    NSString *dateString = [formatter stringFromDate:date];
    
    return dateString;
}


+(NSDate*) convertDateFromString:(NSString*)uiDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    NSDate *date=[formatter dateFromString:uiDate];
    
    NSLog(@"data %@",date);
    return date;
}

+ (NSDate *)stringDateToDate:(NSString *)dateString {
//    @"2013-03-24 10:45:32"
    NSString *currentDateString = dateString;
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
    return [dateFormater dateFromString:currentDateString];
}

//1406702751547
+ (NSString *)dateAllStringFromString:(NSString *)timeString
{
    return [MTool dateStringFromString:timeString toFormat:@"YYYY-MM-dd HH:mm:ss"];
}

+ (NSString *)datePartStringFromString:(NSString *)timeString
{
    return [MTool dateStringFromString:timeString toFormat:@"YYYY-MM-dd"];
}


/**
 时间字符串转时间戳字符串

 @param timeStr 格式化的时间字符串
 @param type @"yyyy-MM-dd"
 @return 时间戳字符串
 */
+ (NSString *)timeStrToTimeStampStr:(NSString *)timeStr type:(NSString *)type {
    //定义日期格式化对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //创建格式化标准
    [dateFormatter setDateFormat:type];
    //对传入字符串进行格式化操作
    NSDate *destDate = [dateFormatter dateFromString:timeStr];
    NSString *stimeSp = [NSString stringWithFormat:@"%.0ld", (long)[destDate timeIntervalSince1970]];
    return stimeSp;
}


#pragma mark - 将13位时间转换为想要的时间格式
/**
 * @brief   将13位时间转换为想要的时间格式
 * @param   timeString    13位时间
 * @param   toFormat    格式（如：YYYY-MM-dd HH:mm:ss）
 * @return  NSString 时间
 */
+ (NSString *)dateStringFromString:(NSString *)timeString toFormat:(NSString *)toFormat
{
    if (timeString.length >= 10)
    {
        NSTimeInterval timeInterval = [timeString doubleValue]/1000;
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:toFormat];
        
        NSString *str = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
        
        return str;
    } else {
        NSTimeInterval timeInterval = [timeString doubleValue];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:toFormat];
        
        NSString *str = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
        
        return str;
    }
    return @"";
}


+ (NSString *)dateToString:(NSDate *)sender {
//    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now = [sender timeIntervalSince1970] * 1000;
//    NSTimeInterval now = [sender timeIntervalSince1970];
    
    NSMutableString *stringTime = [NSMutableString stringWithFormat:@"%lld", (long long)now];
//    if ([stringTime length] < 13) {
//        while ([stringTime length] < 13) {
//            [stringTime appendString:@"0"];
//        }
//    }
    
    return stringTime;
}

+ (NSString *)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:0 // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    return jsonString;
}

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+ (id)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    id obj = [NSJSONSerialization JSONObjectWithData:jsonData
                                             options:NSJSONReadingMutableContainers
                                               error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return obj;
}

//存储当前刷新状态
+ (BOOL)storeCurrentRefresh:(NSString *)refresh
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:refresh];
    if (personData) {
        [myDefault setObject:personData forKey:@"refresh"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}
//存储当前刷新时间间隔
+ (BOOL)storeCurrentRefreshTimeInterval:(NSString *)interval
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:interval];
    if (personData) {
        [myDefault setObject:personData forKey:@"timeInterval"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}

+ (BOOL)getCurrentRefresh
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"refresh"];
    if (personData) {
        return  [[NSKeyedUnarchiver unarchiveObjectWithData:personData] boolValue];
    }
    return nil;
}

+ (NSInteger)getCurrentRefreshTimeInterval
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"timeInterval"];
    if (personData) {
        return  [[NSKeyedUnarchiver unarchiveObjectWithData:personData] integerValue];
    }
    return 0;
}

#pragma mark - 正则校验
+ (BOOL)isValidateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(17[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}

/*车牌号验证 MODIFIED BY HELENSONG*/
#pragma 车牌号验证
+ (BOOL) checkCarNumber:(NSString *) CarNumber{
    NSString *bankNum = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4,5}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",bankNum];
    BOOL isMatch = [pred evaluateWithObject:CarNumber];
    return isMatch;
}



#pragma mark 存储数据缓存更新时间
+ (BOOL)storeCurrentUpDataTime:(NSString *)updataTime {
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:updataTime];
    if (personData) {
        [myDefault setObject:personData forKey:@"updataTime"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}
+ (NSString *)getCurrentUpDataTime {
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"updataTime"];
    if (personData) {
        return  [NSKeyedUnarchiver unarchiveObjectWithData:personData];
    }
    return nil;
}


#pragma mark 存储当前登陆状态
+ (BOOL)storeCurrentLoginState:(NSString *)loginStr
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:loginStr];
    if (personData) {
        [myDefault setObject:personData forKey:@"loginState"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}

+ (NSString *)getCurrentLastLoginState
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"loginState"];
    if (personData) {
        return  [NSKeyedUnarchiver unarchiveObjectWithData:personData];
    }
    return nil;
}

#pragma mark 存储当前返回的信息
+ (BOOL)storeCurrentUserName:(NSString *)userName
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:userName];
    if (personData) {
        [myDefault setObject:personData forKey:@"userName"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}

+ (BOOL)storeCurrentUserPwd:(NSString *)userPwd
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:userPwd];
    if (personData) {
        [myDefault setObject:personData forKey:@"userPwd"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}

+ (NSString *)getUserName
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"userName"];
    if (personData) {
        return  [NSKeyedUnarchiver unarchiveObjectWithData:personData];
    }
    return nil;
}

+ (NSString *)getUserPwd
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"userPwd"];
    if (personData) {
        return  [NSKeyedUnarchiver unarchiveObjectWithData:personData];
    }
    return nil;
}




+(BOOL)storeCurrentMessage:(NSDictionary *)curretnPersonDic
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:curretnPersonDic];
    if (personData) {
        [myDefault setObject:personData forKey:@"login"];
        [myDefault synchronize];
        return YES;
    }
    return NO;
}

+ (NSMutableDictionary  *)getCurrentMessage
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:@"login"];
    if (personData) {
        return  [NSKeyedUnarchiver unarchiveObjectWithData:personData];
    }
    return nil;
}

//清除当前信息
+ (void)removeCurrentMessage
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    [myDefault removeObjectForKey:@"login"];
}


+ (void)showMessageToWidow:(NSString *)message key:(NSInteger)key {
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    LoadingView *view = [[LoadingView alloc] initWithFrame:appDelegate.window.bounds withText:message];
    view.tag = key;
    [appDelegate.window addSubview:view];
}

+ (void)removeMessageForKey:(NSInteger)key {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    LoadingView *view = (LoadingView *)[keyWindow viewWithTag:key];
    [view removeFromSuperview];
}



/**
 * Retain a formated string with a real date string
 *
 * @param dateString a real date string, which can be converted to a NSDate object
 *
 * @return a string that will be x分钟前/x小时前/昨天/x天前/x个月前/x年前
 */
+ (NSString *)timeInfoWithDateString:(NSString *)dateString {
    // 把日期字符串格式化为日期对象
    NSDate *date = nil;
    if (dateString.length == 13)
    {
        NSTimeInterval timeInterval = [dateString doubleValue]/1000;
        date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
        date = [MTool getNowDateFromatAnDate:date];
    } else {
        return @"";
    }
    
    NSDate *curDate = [NSDate date];
    curDate = [MTool getNowDateFromatAnDate:curDate];
//    NSTimeInterval time = -[date timeIntervalSinceDate:curDate];
    
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    NSDateComponents *curDateComps;// = [[NSDateComponents alloc] init];
    curDateComps = [calendar components:unitFlags fromDate:curDate];
    
    NSDateComponents *dateComps;// = [[NSDateComponents alloc] init];
    dateComps = [calendar components:unitFlags fromDate:date];
    
    

    if ([curDateComps day] == [dateComps day]) {
        return [MTool dateStringFromString:dateString toFormat:@"HH:mm"];
    } else {
        return [NSString stringWithFormat:@"%ld天前", (long)abs([MTool intervalSinceNow:dateString])];
    }
    
    return @"1小时前";
}


+ (int)intervalSinceNow: (NSString *) theDate
{
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *d=[date dateFromString:theDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSince1970:0];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=now-late;
    
    if (cha/86400>1)
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        return [timeString intValue];
    }
    return -1;
}


+ (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate
{
    //设置源日期时区
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    //设置转换后的目标日期时区
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    return destinationDateNow;
}


//+ (UIImage *)aa {
//    //生成JPG图片，因为png太大了
//    NSMutableString *tempFileName = [NSMutableString stringWithString:[[picFilePath componentsSeparatedByString:@"."] objectAtIndex:0]];
//
//    [tempFileName appendString:@".jpg"];
//    picFilePath = [NSString stringWithString:tempFileName];
//
//    NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/tempUpLoadImage.jpg"];
//    [UIImageJPEGRepresentation(image, 0.75) writeToFile:jpgPath atomically:YES];
//
//    image = [[UIImage alloc]initWithContentsOfFile:jpgPath];
//
//    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:postParems];
//
//    NSArray *keysArrsy = [tempDic allKeys];
//    for (NSInteger i = 0; i < [tempDic count]; i++) {
//        NSObject *temp = [tempDic objectForKey:[keysArrsy objectAtIndex:i]];
//        if ([temp isKindOfClass:[UIImage class]]) {
//            [tempDic setObject:image forKeyedSubscript:[keysArrsy objectAtIndex:i]];
//            postParems = [NSDictionary dictionaryWithDictionary:tempDic];
//            break;
//        }
//        NSLog(@"sdsfdsfsdsdfsdfsfsd, %@", temp);
//    }
//    
//    //生成JPG end
//}

/**
 * @brief   通过text view中的文字与宽度，计算出高度
 * @param   textView 要计算的textView
 * @return  CGSize  计算后的大小
 */
+ (CGSize)contentSizeHeightOfTextView:(UITextView *)textView {
    CGSize textViewSize = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, FLT_MAX)];
    
    return textViewSize;
}

/**
 * @brief   通过label中的文字与宽度，计算出高度
 * @param   label 要计算的label
 * @return  CGSize  计算后的大小
 */
+ (CGSize)contentSizeHeightOfLabel:(UILabel *)label {
    CGSize labelSize = [label sizeThatFits:CGSizeMake(label.frame.size.width, FLT_MAX)];
    
    return labelSize;
}

/**
 * @brief   通过label中的文字与高度，计算出宽度
 * @param   label 要计算的label
 * @return  CGSize  计算后的大小
 */
+ (CGSize)contentSizeWidthOfLabel:(UILabel *)label {
    CGSize labelSize = [label sizeThatFits:CGSizeMake(FLT_MAX, label.frame.size.height)];
    
    return labelSize;
}


/**
 * @brief   复制View
 * @param   view 要复制的view
 * @return  UIView  复制的View
 */
+ (UIView*)duplicate:(UIView*)view
{
    NSData * tempArchive = [NSKeyedArchiver archivedDataWithRootObject:view];
    return [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
}


/**
 * @brief   检查是否是数组，数组长度是否大于0
 * @param   id 要检查的对象
 * @return  BOOL
 */
+ (BOOL)checkingIsArray:(id)sender {
    
    if (sender) {
        if ([sender isKindOfClass:[NSArray class]] || [sender isKindOfClass:[NSMutableArray class]]) {
            if ([sender count] > 0) {
                return YES;
            }
        }
    }
    
    return NO;
}

/**
 * @brief   检查是否是string，长度是否大于0
 * @param   id 要检查的对象
 * @return  BOOL
 */
+ (BOOL)checkingIsString:(id)sender {
    if ([sender isKindOfClass:[NSNull class]]) sender = @"";
    if (sender) {
        if ([sender isKindOfClass:[NSString class]] ||[sender isKindOfClass:[NSMutableString class]]) {
            if ([sender length] > 0) {
                return YES;
            }
        }
    }
    return NO;
}

/**
 * @brief   检查是否是Dic，长度是否大于0
 * @param   id 要检查的对象
 * @return  BOOL
 */
+ (BOOL)checkingIsDic:(id)sender {
    if (sender) {
        if ([sender isKindOfClass:[NSDictionary class]] ||[sender isKindOfClass:[NSMutableDictionary class]]) {
            if ([sender count] > 0) {
                return YES;
            }
        }
    }
    return NO;
}



/**
 * @brief   读取plist文件，得到内容为DIC
 * @param   fileName plist名
 * @return  NSMutableDictionary
 */
+ (NSMutableDictionary *)readPlistToDic:(NSString *)fileName {
    //获取应用程序沙盒的Documents目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename=[plistPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", fileName]];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
    if (data) {
        if ([data isKindOfClass:[NSMutableDictionary class]]) {
            return data;
        }
    }
    return nil;
}

/**
 * @brief   将DIC写入到plist文件
 * @param   fileName plist名
 * @param   dataDic DIC
 */
+ (void)pushDicToPlist:(NSMutableDictionary *)dataDic fileName:(NSString *)fileName {
    
    //获取应用程序沙盒的Documents目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename=[plistPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", fileName]];
    
    //输入写入
    [dataDic writeToFile:filename atomically:YES];
    
//    //那怎么证明我的数据写入了呢？读出来看看
//    NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
//    NSLog(@"%@", data1);
}





/**
 * @brief   读取plist文件，得到内容为Array
 * @param   fileName plist名
 * @return  NSMutableArray
 */
+ (NSMutableArray *)readPlistToArray:(NSString *)fileName {
    //获取应用程序沙盒的Documents目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename=[plistPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", fileName]];
    NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:filename];
    if (data) {
        if ([data isKindOfClass:[NSMutableArray class]]) {
            return data;
        }
    }
    return nil;
}

/**
 * @brief   将Array写入到plist文件
 * @param   fileName plist名
 * @param   dataArray array
 */
+ (void)pushArrayToPlist:(NSMutableArray *)dataArray fileName:(NSString *)fileName {
    //获取应用程序沙盒的Documents目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename=[plistPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", fileName]];
    //输入写入
    [dataArray writeToFile:filename atomically:YES];
    
//    //那怎么证明我的数据写入了呢？读出来看看
//    NSMutableArray *data1 = [[NSMutableArray alloc] initWithContentsOfFile:filename];
//    NSLog(@"%@", data1);
}


/**
 * @brief   文件是否存在
 * @param   path 路径
 * @param   isCreate 如果不存在，是否创建  YES创建、NO不创建
 * @param   BOOL
 */
+ (BOOL)fileExists:(NSString *)path isCreate:(BOOL)isCreate{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    
    if ([fileManager fileExistsAtPath:path]) {//如果文件存在
        NSLog(@"文件已经存在");
        return YES;
    } else {
        if (isCreate) {
            [fileManager createFileAtPath:path contents:nil attributes:nil];
        }
    }
    return NO;
}


/**
 * @brief   文件是否存在在Documents目录下
 * @param   name 文件名
 * @param   isCreate 如果不存在，是否创建  YES创建、NO不创建
 * @param   BOOL
 */
+ (BOOL)fileExistsForName:(NSString *)name isCreate:(BOOL)isCreate {
    //获取应用程序沙盒的Documents目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename=[plistPath stringByAppendingPathComponent:name];
    
    return [MTool fileExists:filename isCreate:isCreate];
}



/**
 * @brief   将信息写入到plist
 * @param   sender 信息DIC
 */
+ (void)pushDicToPlist:(NSMutableDictionary *)sender name:(NSString *)name{
    // 筛选null，避免写入不成功
    for (id key in sender.allKeys.reverseObjectEnumerator) {
        if ([[sender objectForKey:key] isKindOfClass:[NSNull class]]) {
            [sender setObject:@"" forKey:key];
        }
    }
    [MTool fileExistsForName:[NSString stringWithFormat:@"%@.plist", name] isCreate:YES];
    [MTool pushDicToPlist:sender fileName:name];
}

/**
 * @brief   得到plist信息
 * @return  NSString 文件名
 */
+ (NSDictionary *)getDicFromPlist:(NSString *)name {
    //获取应用程序沙盒的Documents目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename=[plistPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", name]];
    
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
    if (data) {
        if ([data isKindOfClass:[NSMutableDictionary class]]) {
            return data;
        }
    }
    return nil;
}


/**
 * @param sender 地区信息数组
 * @param province 要查询的省
 * @return NSDictionary 省信息
 */
+ (NSDictionary *)getProvince:(NSArray *)sender province:(NSString *)province {
    for (NSDictionary *temp in sender) {
        if ([MTool checkingIsDic:temp]) {
            if ([[temp objectForKey:@"name"] isEqualToString:province] || [[temp objectForKey:@"code"] isEqualToString:province]) {
                return temp;
            }
        }
    }
    return nil;
}

/**
 * @param sender 地区信息数组
 * @param city 要查询的市
 * @return NSDictionary 市信息
 */
+ (NSDictionary *)getCity:(NSArray *)sender city:(NSString *)city {
    for (NSDictionary *temp in sender) {
        if ([MTool checkingIsDic:temp]) {
            if ([[temp objectForKey:@"name"] isEqualToString:city]) {
                return temp;
            }
        }
    }
    return nil;
}
//
//+ (void)cityMessageMark:(struct CityMessage)city toCityMessage:(struct CityMessage)sender {
//    city.province = sender.province;
//    CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)
//}


+ (void)callPhone:(NSString *)phoneNum {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phoneNum]]];
}


+ (UIImage *)annotationImage:(NSDictionary *)sender {
    if ([MTool checkingIsDic:sender]) {
        NSString *operator = [sender objectForKey:@"operator"];
        if ([operator isEqualToString:@"国家电网"] || [operator isEqualToString:@"电力公司"]) {
            return  [UIImage imageNamed:@"充电桩查询-国家电网New"];
        } else if ([operator isEqualToString:@"普天新能源"]) {
            return [UIImage imageNamed:@"充电桩查询-普天New"];
        } else if ([operator isEqualToString:@"星星充电"]) {
            return [UIImage imageNamed:@"充电桩查询-星星New"];
        } else if ([operator isEqualToString:@"特锐德"] || [operator isEqualToString:@"特来电"] || [operator isEqualToString:@"北汽特来电"]) {
            return [UIImage imageNamed:@"充电桩查询-特锐德New"];
        } else if ([operator isEqualToString:@"特斯拉"]) {
            return [UIImage imageNamed:@"充电桩查询-特斯拉New"];
        } else if ([operator isEqualToString:@"依威能源"]) {
            return [UIImage imageNamed:@"充电桩查询-依偎能源New"];
        } else if ([operator isEqualToString:@"南方电网"]) {
            return [UIImage imageNamed:@"充电桩查询-南方电网New"];
        }
    }
    
    return  [UIImage imageNamed:@"充电桩查询-充电桩New"];
}



+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size {
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}



//+(NSString *)identifier
//{
//    NSString *key = @"com.app.keychain.uuid";
//    KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:key accessGroup:nil];
//    
//    NSString *strUUID = [keychainItem objectForKey:(__bridge id)kSecValueData];
//    
//    if (strUUID.length <= 0) {
//        strUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
//        
//        [keychainItem setObject:@"uuid" forKey:(__bridge id)kSecAttrAccount];
//        [keychainItem setObject:strUUID forKey:(__bridge id)kSecValueData];
//    }
//    
//    return strUUID;
//}


/**
 * @brief   设置圆角
 * @param   radius 圆角度数
 * @param   view
 */
+ (void)setViewRadius:(CGFloat)radius view:(id)view {
    ((UIView *)view).layer.cornerRadius = radius;
    ((UIView *)view).layer.masksToBounds = YES;
}

/**
 * @brief   描边
 * @param   borderWidth 边宽度
 * @param   color 颜色
 * @param   view
 */
+ (void)setViewBorder:(CGFloat)borderWidth color:(UIColor *)color view:(id)view {
    ((UIView *)view).layer.borderColor = color.CGColor;
    ((UIView *)view).layer.borderWidth = borderWidth;
}

/**
 * @brief   描边并加圆角
 * @param   borderWidth 边宽度
 * @param   color 颜色
 * @param   radius 圆角度数
 * @param   view
 */
+(void)setViewRadiusAndBorder:(CGFloat)borderWidth color:(UIColor *)color radius:(CGFloat)radius view:(id)view {
    ((UIView *)view).layer.cornerRadius = radius;
    ((UIView *)view).layer.masksToBounds = YES;
    ((UIView *)view).layer.borderColor = color.CGColor;
    ((UIView *)view).layer.borderWidth = borderWidth;
}

/**
 * @brief   设置UITextField左边距
 * @param   textField textField
 * @param   leftWidth 距离
 */
+ (void)setTextFieldLeftPadding:(UITextField *)textField forWidth:(CGFloat)leftWidth {
    CGRect frame = textField.frame;
    frame.size.width = leftWidth;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = leftview;
}


#pragma mark -手机别名
+(NSString *)phoneName
{
    return [[UIDevice currentDevice] name];
}


#pragma mark -手机系统版本
/**
 *  手机系统版本
 *
 *  @return e.g. 8.0
 */
+(NSString *)phoneVersion{
    return [[UIDevice currentDevice] systemVersion];
}

#pragma mark -手机型号
//这个方法只能获取到iPhone、iPad这种信息，无法获取到是iPhone 4、iPhpone5这种具体的型号。
/**
 *  手机型号
 *
 *  @return e.g. iPhone
 */
+(NSString *)phoneModel{
    return [[UIDevice currentDevice] model];
}


#pragma mark - 设备版本
//这个代码可以获取到具体的设备版本（已更新到iPhone 6s、iPhone 6s Plus），缺点是：采用的硬编码。具体的对应关系可以参考：https://www.theiphonewiki.com/wiki/Models
//这个方法可以通过AppStore的审核，放心用吧。
/**
 *  设备版本
 *
 *  @return e.g. iPhone 5S
 */
+ (NSString *)DeviceVersion {
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    //iPhone
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    
    //iPod
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
    
    //iPad
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"iPad2,4"])      return @"iPad 2 (32nm)";
    if ([deviceString isEqualToString:@"iPad2,5"])      return @"iPad mini (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,6"])      return @"iPad mini (GSM)";
    if ([deviceString isEqualToString:@"iPad2,7"])      return @"iPad mini (CDMA)";
    
    if ([deviceString isEqualToString:@"iPad3,1"])      return @"iPad 3(WiFi)";
    if ([deviceString isEqualToString:@"iPad3,2"])      return @"iPad 3(CDMA)";
    if ([deviceString isEqualToString:@"iPad3,3"])      return @"iPad 3(4G)";
    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([deviceString isEqualToString:@"iPad3,5"])      return @"iPad 4 (4G)";
    if ([deviceString isEqualToString:@"iPad3,6"])      return @"iPad 4 (CDMA)";
    
    if ([deviceString isEqualToString:@"iPad4,1"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad4,2"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad4,3"])      return @"iPad Air";
    if ([deviceString isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
    if ([deviceString isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    
    if ([deviceString isEqualToString:@"iPad4,4"]
        ||[deviceString isEqualToString:@"iPad4,5"]
        ||[deviceString isEqualToString:@"iPad4,6"])      return @"iPad mini 2";
    
    if ([deviceString isEqualToString:@"iPad4,7"]
        ||[deviceString isEqualToString:@"iPad4,8"]
        ||[deviceString isEqualToString:@"iPad4,9"])      return @"iPad mini 3";
    
    return deviceString;
}

+ (NSString *)getString:(NSString *)string{
    if (string) {
        if ([string isKindOfClass:[NSString class]]) {
            return string;
        }else{
            return [NSString stringWithFormat:@"%@",string];
        }
    }else{
        return @"";
    }
}


/**
 向UserDefault内写入信息

 @param value 写入的信息
 @param key key
 */
+ (void)setUserDefaultsMsgWithValue:(id)value ForKey:(NSString *)key {
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:value];
    if (personData) {
        [myDefault setObject:personData forKey:key];
        [myDefault synchronize];
    }
}


/**
 获取UserDefault内信息

 @param key key
 @return 返回值
 */
+ (id)getUserDefaultsMsgWithKey:(NSString *)key {
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSData *personData = [myDefault objectForKey:key];
    if (personData) {
        return  [NSKeyedUnarchiver unarchiveObjectWithData:personData];
    }
    return nil;
}


/**
 获取蓝牙权限

 @param vc 当前控制器
 */
+ (void)applyBleRule:(UIViewController *)vc {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"打开蓝牙来允许“充电吧”连接到配件" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }]];
    
    
    [vc presentViewController:alertController animated:YES completion:nil];
}


/**
 清除ios11scrollView类的头部20像素空白
 
 @param vc 控制器
 @param scrollView 需要操作的视图
 */
+ (void)clearScrollViewTopTwentyWhiteWithController:(UIViewController *)vc scrollView:(UIScrollView *)scrollView {
        if (@available(iOS 11.0, *)) {
            scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
        }else {
            vc.automaticallyAdjustsScrollViewInsets = NO;
        }
}

+ (void)addLoadingView:(NSString *)loadingText
{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    LoadingView *view = (LoadingView *)[appDelegate.window viewWithTag:12345678];
    if (view) {
        [view removeFromSuperview];
    }
    LoadingView *newView = [[LoadingView alloc] initWithFrame:appDelegate.window.bounds withText:loadingText];
    newView.tag = 12345678;
    NSLog(@"%@ == ",newView);
    [appDelegate.window addSubview:newView];
    
}

+ (void)removeLoadingView
{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    LoadingView *view = (LoadingView *)[appDelegate.window viewWithTag:12345678];
    if (view) {
        [view removeFromSuperview];
    }
    
}

///**
// 检查图片地址是否正确
//
// @param imageUrl 图片地址
// @return 处理后的图片地址
// */
//+ (NSString *)checkImageURL:(NSString *)imageUrl {
//    if ([MTool checkingIsString:imageUrl]) {
//        if ([imageUrl hasPrefix:@"http"]) {
//            return imageUrl;
//        } else {
//            return [NSString stringWithFormat:@"%@%@", IMAGE_HTTP_HOST, imageUrl];
//        }
//    }
//    return @"";
//}



/**
 把数字格式化成时间

 @param second 数字
 @return 时间字符串
 */
+ (NSString *)convertTime:(CGFloat)second {
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (second/3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    } else {
        [formatter setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [formatter stringFromDate:d];
    return showtimeNew;
}


@end
